<template>
  <div class="body-container">
    <NoticeBar color="#1989fa" background="#ecf9ff" mode="closeable"
      >用户选择上传的图片不经过后台，本站也不存储用户图片!!!</NoticeBar
    >
    <div class="main-box">
      <h3>
        <div class="sign">
          <span class="fast-flicker">头</span>像<span class="flicker">合</span
          >成
        </div>
      </h3>
      <div class="avatar-box">
        <div
          class="img-frame"
          v-loading="makeLoading"
          element-loading-text="制作中..."
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
        >
          <span
            v-if="previewImage == ''"
            class="default-show"
            v-show="previewImage == ''"
          ></span>
          <div v-else>
            <img
              crossOrigin="anonymous"
              v-show="newsAvatarBase64 == ''"
              :src="previewImage"
              id="userAvatar"
            />
            <img v-show="newsAvatarBase64 != ''" :src="newsAvatarBase64" />
          </div>
        </div>
      </div>
      <div class="btn-list">
        <el-upload
          ref="upload"
          :show-file-list="false"
          action
          :before-upload="beforeUploadAction"
          :http-request="handleChange"
        >
          <el-button round>上传图片</el-button>
        </el-upload>
        <Button
          v-if="!isMobile"
          round
          plain
          hairline
          type="success"
          v-show="newsAvatarBase64 != ''"
          @click="downloadFile"
          >下载图片</Button
        >
        <Button
          v-else
          round
          plain
          hairline
          type="success"
          v-show="newsAvatarBase64 != ''"
          >长按图片保存</Button
        >
      </div>
    </div>
    <div class="footer-container" v-show="!cropperVisible">
      <el-scrollbar>
        <div class="flex-content">
          <p
            v-for="(item, index) in bgList"
            :key="item"
            :class="'img-item ' + (chooseIndex == index ? 'active' : '')"
            :data-img="index"
            @click="synthesisImg($event)"
          >
            <img :id="'a_' + index" :src="item" />
          </p>
        </div>
      </el-scrollbar>
    </div>
    <Cropper
      v-if="cropperVisible"
      :imagePath="imagePath"
      fileType="base64"
      cropSize="200"
      quality="0.8"
      @save="onSave"
      @cancel="onCancel"
    />
  </div>
</template>
<script>
import Cropper from "vue3-cropper";
import "vue3-cropper/lib/vue3-cropper.css";
import { reactive, toRefs } from "@vue/reactivity";
import { Notify, NoticeBar, Button } from "vant";
import { onMounted } from "@vue/runtime-core";
const URL = window.URL || window.webkitURL;
export default {
  name: "index",
  components: { Cropper, NoticeBar, Button },
  setup() {
    const state = reactive({
      cropperVisible: false,
      imagePath: "",
      previewImage: "",
      isStopRun: false,
      imgSize: 10,
      newsAvatarBase64: "",
      bgList: [],
      makeLoading: false,
      chooseIndex: -1,
      isMobile: false,
    });
    onMounted(() => {
      let ism= navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      )
      state.isMobile =ism!=null
      console.log(ism,66)
    });
    for (let index = 0; index < 6; index++) {
      state.bgList.push(require("../assets/image/pic" + (index + 1) + ".png"));
    }

    const synthesisImg = (e) => {
      if (state.previewImage === "") {
        Notify({ type: "warning", message: "请选图片" });
        return;
      }
      if (state.makeLoading) {
        Notify({ type: "primary", message: "努力合成中..." });
        return;
      }
      let beginTime = new Date().getTime();
      let id = e.target.dataset.img;
      state.chooseIndex = id;
      state.makeLoading = true;
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      var width = 640 * 2;
      var height = width;
      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(document.querySelector("#userAvatar"), 0, 0, width, height);
      ctx.drawImage(document.querySelector("#a_" + id), 0, 0, width, height);
      state.newsAvatarBase64 = canvas.toDataURL("image/jpeg");
      let totalConsumedTime = new Date().getTime() - beginTime;
      //防止加载太快 最小等待时间500毫秒
      let minMS = 500;
      if (minMS > totalConsumedTime) {
        setTimeout(() => {
          state.makeLoading = false;
        }, minMS - totalConsumedTime);
      } else {
        state.makeLoading = false;
      }
    };

    const beforeUploadAction = (file) => {
      //文件上传前
      var fileType = file.type;
      console.log(fileType, 456);
      if (fileType.indexOf("image") < 0) {
        Notify({ type: "warning", message: "请上传图片" });
        state.isStopRun = true;
        return false;
      }
      const isJpgOrPng =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg";
      if (!isJpgOrPng) {
        Notify({ type: "warning", message: "上传图片格式不正确" });
        state.isStopRun = true;
      }
      const isLtSize = file.size < state.imgSize * 1024 * 1024;
      if (!isLtSize) {
        Notify({
          type: "warning",
          message: "图片大小不能超过" + state.imgSize + "MB!",
        });
        state.isStopRun = true;
      }
      return isJpgOrPng && isLtSize;
    };
    const handleChange = (info) => {
      let file = info.file;
      state.imagePath = URL.createObjectURL(file);
      state.cropperVisible = true;
    };
    const onSave = (res) => {
      //裁剪后保存
      if (typeof res === "string") {
        state.previewImage = res;
      } else {
        state.previewImage = URL.createObjectURL(res);
      }
      state.cropperVisible = false;
      state.isShowFooter = false;
    };

    const onCancel = () => {
      state.cropperVisible = false;
    };
    const downloadFile = () => {
      var data = state.newsAvatarBase64;
      var filename = Date.now();
      //创建一个具有指定的命名空间URI和限定名称的元素
      var save_link = document.createElementNS(
        "http://www.w3.org/1999/xhtml",
        "a"
      );
      save_link.href = data;
      save_link.download = filename;
      // 绑定下载事件
      var event = document.createEvent("MouseEvents");
      event.initMouseEvent(
        "click",
        true,
        false,
        window,
        0,
        0,
        0,
        0,
        0,
        false,
        false,
        false,
        false,
        0,
        null
      );
      save_link.dispatchEvent(event);
    };
    
   
    return {
      ...toRefs(state),
      synthesisImg,
      onSave,
      onCancel,
      beforeUploadAction,
      handleChange,
      downloadFile
    };
  },
};
</script>
<style lang="less" scoped>
.body-container {
  position: relative;
  width: 100%;
  height: 100vh;
  background: url("../assets/image/bg.jpg");
  background-size: cover;
  max-width: 7.5rem;
  margin: 0 auto;
  .main-box {
    position: absolute;
    width: 100%;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -50%);
    max-width: 7.5rem;
    margin: 0 auto;
    h3 {
      text-align: center;
      color: #fdf9c6;
      font-weight: bold;
      font-size: 24px;
      letter-spacing: 30px;
      margin-left: 0.3rem;
    }
    .avatar-box {
      position: relative;
      width: 6.4rem;
      height: 3.95rem;
      margin: 0 auto;
      background: url("../assets/image/bg-2.png");
      background-size: 100% 100%;
      .img-frame {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 2.52rem;
        height: 2.52rem;
        border: 4px solid #9b73f7;
        img {
          width: 100%;
          height: 100%;
          background-size: cover;
        }
      }
    }
    .btn-list {
      text-align: center;
      height: 60px;
      .van-button {
        margin-top: 0.1rem;
        width: 3.6rem;
        line-height: 40px;
        height: 40px;
      }
    }
    .btn-save {
      width: 3rem;
    }
    .el-button {
      width: 3.6rem;
      margin: 0 auto;
      text-align: center;
      display: block;
    }
  }
  .footer-container {
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 10;
    width: 100%;
    background: #9b74f5;
    .flex-content {
      display: flex;
      .img-item {
        position: relative;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 1.4rem;
        height: 1.4rem;
        margin: 0.2rem;
        background-repeat: no-repeat;
        background-size: 100%;
        background-position: 50% 50%;
        img {
          width: 100%;
          height: 1rem;
          user-select: none;
          pointer-events: none;
          -webkit-touch-callout: none;
        }
      }
      .img-item.active::before {
        position: absolute;
        left: 50%;
        top: -10px;
        content: "♥";
        color: red;
        font-weight: bold;
        font-size: 18px;
        transform: translate(-50%, 0);
      }
    }
  }
}
.sign {
  background-image: radial-gradient(
    ellipse 50% 35% at 50% 50%,
    #6b1839,
    transparent
  );
  letter-spacing: 2;
  font-family: "Clip";
  text-transform: uppercase;
  font-size: 24px;
  color: #ffe6ff;
  text-shadow: 0 0 0.6rem #ffe6ff, 0 0 1.5rem #ff65bd,
    -0.2rem 0.1rem 1rem #ff65bd, 0.2rem 0.1rem 1rem #ff65bd,
    0 -0.5rem 2rem #ff2483, 0 0.5rem 3rem #ff2483;
  animation: shine 2s forwards, flicker 3s infinite;
}

@keyframes blink {
  0%,
  22%,
  36%,
  75% {
    color: #ffe6ff;
    text-shadow: 0 0 0.6rem #ffe6ff, 0 0 1.5rem #ff65bd,
      -0.2rem 0.1rem 1rem #ff65bd, 0.2rem 0.1rem 1rem #ff65bd,
      0 -0.5rem 2rem #d64584, 0 0.5rem 3rem #d64584;
  }
  28%,
  33% {
    color: #ff65bd;
    text-shadow: none;
  }
  82%,
  97% {
    color: #d64584;
    text-shadow: none;
  }
}

.flicker {
  animation: shine 2s forwards, blink 3s 2s infinite;
}

.fast-flicker {
  animation: shine 2s forwards, blink 10s 1s infinite;
}

@keyframes shine {
  0% {
    color: #d64584;
    text-shadow: none;
  }
  100% {
    color: #ffe6ff;
    text-shadow: 0 0 0.6rem #ffe6ff, 0 0 1.5rem #ff65bd,
      -0.2rem 0.1rem 1rem #ff65bd, 0.2rem 0.1rem 1rem #ff65bd,
      0 -0.5rem 2rem #d64584, 0 0.5rem 3rem #d64584;
  }
}

@keyframes flicker {
  from {
    opacity: 1;
  }

  4% {
    opacity: 0.9;
  }

  6% {
    opacity: 0.85;
  }

  8% {
    opacity: 0.95;
  }

  10% {
    opacity: 0.9;
  }

  11% {
    opacity: 0.922;
  }

  12% {
    opacity: 0.9;
  }

  14% {
    opacity: 0.95;
  }

  16% {
    opacity: 0.98;
  }

  17% {
    opacity: 0.9;
  }

  19% {
    opacity: 0.93;
  }

  20% {
    opacity: 0.99;
  }

  24% {
    opacity: 1;
  }

  26% {
    opacity: 0.94;
  }

  28% {
    opacity: 0.98;
  }

  37% {
    opacity: 0.93;
  }

  38% {
    opacity: 0.5;
  }

  39% {
    opacity: 0.96;
  }

  42% {
    opacity: 1;
  }

  44% {
    opacity: 0.97;
  }

  46% {
    opacity: 0.94;
  }

  56% {
    opacity: 0.9;
  }

  58% {
    opacity: 0.9;
  }

  60% {
    opacity: 0.99;
  }

  68% {
    opacity: 1;
  }

  70% {
    opacity: 0.9;
  }

  72% {
    opacity: 0.95;
  }

  93% {
    opacity: 0.93;
  }

  95% {
    opacity: 0.95;
  }

  97% {
    opacity: 0.93;
  }

  to {
    opacity: 1;
  }
}
</style>